<template>
  <div class="register-container">
    <div class="register-wrapper">
      <div class="register-header">
        <h1 class="register-title">用户注册</h1>
        <p class="register-subtitle">创建账号，开启皮影艺术之旅</p>
      </div>
      
      <!-- 进度条 -->
      <div class="progress-container">
        <div class="progress-track">
          <div class="progress-bar" :style="{ width: `${currentStep * 50}%` }"></div>
        </div>
        <div class="progress-steps">
          <div 
            v-for="(step, index) in steps" 
            :key="index"
            class="step"
            :class="{ 'active': index <= currentStep, 'completed': index < currentStep }"
          >
            <span class="step-number">{{ index + 1 }}</span>
            <span class="step-label">{{ step }}</span>
          </div>
        </div>
      </div>
      
      <!-- 注册表单 -->
      <form @submit.prevent="handleSubmit" class="register-form">
        <!-- 第一步：基础信息 -->
        <div v-if="currentStep === 0" class="form-step">
          <div class="form-group">
            <label for="phone" class="form-label">手机号码</label>
            <input 
              type="tel" 
              id="phone" 
              v-model="registerForm.phone"
              class="form-input" 
              placeholder="请输入手机号码"
              :class="{ 'focused': focusedInput === 'phone', 'error': errors.phone }"
              @focus="focusedInput = 'phone'"
              @blur="focusedInput = ''"
              maxlength="11"
            >
            <span v-if="errors.phone" class="error-message">{{ errors.phone }}</span>
          </div>
          
          <div class="form-group">
            <label for="verificationCode" class="form-label">验证码</label>
            <div class="verification-wrapper">
              <input 
                type="text" 
                id="verificationCode" 
                v-model="registerForm.verificationCode"
                class="form-input" 
                placeholder="请输入验证码"
                :class="{ 'focused': focusedInput === 'verificationCode', 'error': errors.verificationCode }"
                @focus="focusedInput = 'verificationCode'"
                @blur="focusedInput = ''"
                maxlength="6"
              >
              <button 
                type="button" 
                class="send-code-btn"
                :disabled="countdown > 0"
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
              </button>
            </div>
            <span v-if="errors.verificationCode" class="error-message">{{ errors.verificationCode }}</span>
          </div>
          
          <div class="form-group">
            <label for="password" class="form-label">设置密码</label>
            <div class="password-input-wrapper">
              <input 
                :type="showPassword ? 'text' : 'password'" 
                id="password" 
                v-model="registerForm.password"
                class="form-input" 
                placeholder="请设置6-20位密码"
                :class="{ 'focused': focusedInput === 'password', 'error': errors.password }"
                @focus="focusedInput = 'password'"
                @blur="focusedInput = ''"
              >
              <button 
                type="button" 
                class="toggle-password" 
                @click="showPassword = !showPassword"
              >
                {{ showPassword ? '隐藏' : '显示' }}
              </button>
            </div>
            <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
          </div>
        </div>
        
        <!-- 第二步：兴趣选择 -->
        <div v-if="currentStep === 1" class="form-step">
          <div class="form-group">
            <label class="form-label">感兴趣的皮影内容</label>
            <div class="interest-options">
              <label 
                v-for="interest in interestOptions" 
                :key="interest.value"
                class="interest-option"
              >
                <input 
                  type="checkbox" 
                  :value="interest.value"
                  v-model="registerForm.interests"
                >
                <span class="interest-text">{{ interest.label }}</span>
              </label>
            </div>
            <span v-if="errors.interests" class="error-message">{{ errors.interests }}</span>
          </div>
          
          <div class="form-group">
            <label for="username" class="form-label">昵称</label>
            <input 
              type="text" 
              id="username" 
              v-model="registerForm.username"
              class="form-input" 
              placeholder="请输入昵称"
              :class="{ 'focused': focusedInput === 'username', 'error': errors.username }"
              @focus="focusedInput = 'username'"
              @blur="focusedInput = ''"
            >
            <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
          </div>
          
          <div class="form-group">
            <label class="form-label">性别</label>
            <div class="gender-options">
              <label class="gender-option">
                <input type="radio" value="male" v-model="registerForm.gender">
                <span class="gender-text">男</span>
              </label>
              <label class="gender-option">
                <input type="radio" value="female" v-model="registerForm.gender">
                <span class="gender-text">女</span>
              </label>
              <label class="gender-option">
                <input type="radio" value="other" v-model="registerForm.gender">
                <span class="gender-text">保密</span>
              </label>
            </div>
          </div>
        </div>
        
        <!-- 第三步：完成注册 -->
        <div v-if="currentStep === 2" class="form-step">
          <div class="completion-card">
            <div class="completion-icon">✓</div>
            <h3 class="completion-title">即将完成注册</h3>
            <p class="completion-subtitle">请确认您的信息无误</p>
            
            <div class="info-summary">
              <div class="info-item">
                <span class="info-label">手机号码：</span>
                <span class="info-value">{{ maskPhoneNumber(registerForm.phone) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">昵称：</span>
                <span class="info-value">{{ registerForm.username }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">性别：</span>
                <span class="info-value">{{ getGenderText(registerForm.gender) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">感兴趣的内容：</span>
                <span class="info-value">{{ getInterestLabels(registerForm.interests).join('、') }}</span>
              </div>
            </div>
            
            <div class="agreement">
              <label class="agreement-label">
                <input type="checkbox" v-model="registerForm.agreedToTerms">
                <span>我已阅读并同意<a href="#">《用户协议》</a>和<a href="#">《隐私政策》</a></span>
              </label>
              <span v-if="errors.agreedToTerms" class="error-message">{{ errors.agreedToTerms }}</span>
            </div>
          </div>
        </div>
        
        <!-- 导航按钮 -->
        <div class="form-actions">
          <button 
            type="button" 
            class="btn btn-secondary"
            v-if="currentStep > 0"
            @click="previousStep"
          >
            上一步
          </button>
          <div class="btn-primary-container">
            <button 
              type="submit" 
              class="btn btn-primary"
              :disabled="isSubmitting || !isStepValid"
            >
              <span v-if="isSubmitting" class="loading-spinner"></span>
              <span v-else>
                {{ currentStep === 2 ? '完成注册' : '下一步' }}
              </span>
            </button>
          </div>
        </div>
        
        <!-- 登录链接 -->
        <div v-if="currentStep < 2" class="login-link">
          已有账号？<router-link to="/login">立即登录</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 注册表单数据
const registerForm = ref({
  phone: '',
  verificationCode: '',
  password: '',
  interests: [],
  username: '',
  gender: '',
  agreedToTerms: false
})

// 步骤信息
const steps = ['基础信息', '兴趣选择', '完成注册']
const currentStep = ref(0)
const showPassword = ref(false)
const focusedInput = ref('')
const isSubmitting = ref(false)
const countdown = ref(0)

// 错误信息
const errors = ref({})

// 兴趣选项
const interestOptions = [
  { value: 'history', label: '历史源流' },
  { value: 'craft', label: '制作工艺' },
  { value: 'artists', label: '皮影大师' },
  { value: 'plays', label: '经典剧目' },
  { value: 'culture', label: '文化传承' }
]

// 计算当前步骤是否有效
const isStepValid = computed(() => {
  validateStep()
  switch (currentStep.value) {
    case 0:
      return !errors.value.phone && !errors.value.verificationCode && !errors.value.password
    case 1:
      return !errors.value.username && !errors.value.interests
    case 2:
      return !errors.value.agreedToTerms && registerForm.value.agreedToTerms
    default:
      return false
  }
})

// 验证当前步骤
const validateStep = () => {
  errors.value = {}
  
  switch (currentStep.value) {
    case 0:
      // 验证手机号
      if (!registerForm.value.phone) {
        errors.value.phone = '请输入手机号码'
      } else if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
        errors.value.phone = '请输入有效的手机号码'
      }
      
      // 验证验证码
      if (!registerForm.value.verificationCode) {
        errors.value.verificationCode = '请输入验证码'
      } else if (!/^\d{6}$/.test(registerForm.value.verificationCode)) {
        errors.value.verificationCode = '验证码格式不正确'
      }
      
      // 验证密码
      if (!registerForm.value.password) {
        errors.value.password = '请设置密码'
      } else if (registerForm.value.password.length < 6 || registerForm.value.password.length > 20) {
        errors.value.password = '密码长度应为6-20位'
      }
      break
      
    case 1:
      // 验证昵称
      if (!registerForm.value.username) {
        errors.value.username = '请输入昵称'
      } else if (registerForm.value.username.length < 2 || registerForm.value.username.length > 20) {
        errors.value.username = '昵称长度应为2-20位'
      }
      
      // 验证兴趣
      if (registerForm.value.interests.length === 0) {
        errors.value.interests = '请至少选择一个感兴趣的内容'
      }
      break
      
    case 2:
      // 验证协议
      if (!registerForm.value.agreedToTerms) {
        errors.value.agreedToTerms = '请阅读并同意用户协议和隐私政策'
      }
      break
  }
}

// 发送验证码
const sendVerificationCode = () => {
  if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
    errors.value.phone = '请输入有效的手机号码'
    return
  }
  
  // 模拟发送验证码
  countdown.value = 60
  
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
  
  // 实际项目中这里应该调用API
  console.log('发送验证码到：', registerForm.value.phone)
}

// 下一步
const handleSubmit = () => {
  if (currentStep.value < 2) {
    if (isStepValid.value) {
      currentStep.value++
    }
  } else {
    // 提交注册
    submitRegistration()
  }
}

// 上一步
const previousStep = () => {
  currentStep.value--
}

// 提交注册
const submitRegistration = async () => {
  if (!isStepValid.value) return
  
  isSubmitting.value = true
  
  try {
    // 模拟注册API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 注册成功，保存用户信息到本地存储
    const userInfo = {
      phone: registerForm.value.phone,
      username: registerForm.value.username,
      level: '普通会员'
    }
    
    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    
    // 跳转到首页
    router.push('/home')
  } catch (error) {
    console.error('注册失败:', error)
    alert('注册失败，请稍后重试')
  } finally {
    isSubmitting.value = false
  }
}

// 工具函数：手机号脱敏
const maskPhoneNumber = (phone) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 工具函数：获取性别文本
const getGenderText = (gender) => {
  const genderMap = {
    male: '男',
    female: '女',
    other: '保密'
  }
  return genderMap[gender] || '未设置'
}

// 工具函数：获取兴趣标签
const getInterestLabels = (interestValues) => {
  return interestValues.map(value => {
    const option = interestOptions.find(opt => opt.value === value)
    return option ? option.label : value
  })
}
</script>

<style scoped>
/* 注册容器样式 */
.register-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
  font-family: 'Microsoft YaHei', sans-serif;
}

.register-wrapper {
  width: 100%;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

/* 注册头部 */
.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-title {
  font-size: 28px;
  font-weight: bold;
  color: var(--color-primary);
  margin-bottom: 8px;
  font-family: 'STZhongsong', 'SimSun', serif;
  letter-spacing: 2px;
}

.register-subtitle {
  font-size: 16px;
  color: var(--color-text-medium);
  font-family: 'STKaiti', 'KaiTi', serif;
}

/* 进度条样式 */
.progress-container {
  margin-bottom: 30px;
}

.progress-track {
  width: 100%;
  height: 6px;
  background-color: #eee;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 15px;
}

.progress-bar {
  height: 100%;
  background-color: var(--color-primary);
  transition: width 0.3s ease;
  border-radius: 3px;
}

.progress-steps {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.step-number {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-weight: bold;
  color: #999;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.step-label {
  font-size: 14px;
  color: #999;
  transition: color 0.3s ease;
}

.step.active .step-number {
  background-color: var(--color-primary);
  color: white;
}

.step.active .step-label {
  color: var(--color-primary);
  font-weight: 500;
}

.step.completed .step-number {
  background-color: var(--color-secondary);
  color: white;
  border-color: var(--color-secondary);
}

.step.completed .step-label {
  color: var(--color-secondary);
}

/* 表单样式 */
.register-form {
  width: 100%;
}

.form-step {
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-dark);
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background-color: white;
}

.form-input:focus,
.form-input.focused {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(157, 41, 51, 0.1);
}

.form-input.error {
  border-color: #e74c3c;
}

.error-message {
  display: block;
  margin-top: 5px;
  font-size: 12px;
  color: #e74c3c;
}

/* 验证码输入框 */
.verification-wrapper {
  display: flex;
  gap: 12px;
}

.verification-wrapper .form-input {
  flex: 1;
}

.send-code-btn {
  padding: 12px 20px;
  background-color: var(--color-secondary);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.send-code-btn:hover:not(:disabled) {
  background-color: #c09c25;
}

.send-code-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 密码输入框 */
.password-input-wrapper {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: var(--color-text-medium);
  font-size: 12px;
  cursor: pointer;
  padding: 5px 10px;
  transition: color 0.3s ease;
}

.toggle-password:hover {
  color: var(--color-primary);
}

/* 兴趣选择 */
.interest-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.interest-option {
  flex: 0 0 calc(50% - 6px);
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.interest-option:hover {
  border-color: var(--color-primary);
  background-color: rgba(157, 41, 51, 0.05);
}

.interest-option input[type="checkbox"] {
  margin-right: 8px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.interest-option input[type="checkbox"]:checked + .interest-text {
  color: var(--color-primary);
  font-weight: 500;
}

.interest-text {
  font-size: 14px;
  color: var(--color-text-dark);
  transition: color 0.3s ease;
}

/* 性别选择 */
.gender-options {
  display: flex;
  gap: 20px;
}

.gender-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.gender-option input[type="radio"] {
  margin-right: 8px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.gender-text {
  font-size: 14px;
  color: var(--color-text-dark);
}

/* 完成注册卡片 */
.completion-card {
  text-align: center;
  padding: 30px;
  background-color: #f9f9f9;
  border-radius: 12px;
  margin-bottom: 20px;
}

.completion-icon {
  width: 80px;
  height: 80px;
  background-color: var(--color-secondary);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  margin: 0 auto 20px;
}

.completion-title {
  font-size: 24px;
  color: var(--color-text-dark);
  margin-bottom: 8px;
}

.completion-subtitle {
  font-size: 16px;
  color: var(--color-text-medium);
  margin-bottom: 20px;
}

/* 信息摘要 */
.info-summary {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  text-align: left;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  font-weight: 500;
  color: var(--color-text-medium);
  min-width: 100px;
}

.info-value {
  color: var(--color-text-dark);
  flex: 1;
}

/* 协议同意 */
.agreement {
  text-align: left;
}

.agreement-label {
  display: flex;
  align-items: flex-start;
  font-size: 14px;
  color: var(--color-text-dark);
  cursor: pointer;
}

.agreement-label input[type="checkbox"] {
  margin-right: 8px;
  margin-top: 3px;
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.agreement-label a {
  color: var(--color-primary);
  text-decoration: none;
}

.agreement-label a:hover {
  text-decoration: underline;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 120px;
}

.btn-primary {
  background-color: var(--color-primary);
  color: white;
  border: none;
}

.btn-primary:hover:not(:disabled) {
  background-color: #8a232b;
}

.btn-primary:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-secondary {
  background-color: white;
  color: var(--color-text-dark);
  border: 1px solid #ddd;
}

.btn-secondary:hover {
  background-color: #f5f5f5;
  border-color: #bbb;
}

.btn-primary-container {
  display: flex;
  justify-content: flex-end;
  flex: 1;
}

/* 加载动画 */
.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 登录链接 */
.login-link {
  text-align: center;
  font-size: 14px;
  color: var(--color-text-medium);
}

.login-link a {
  color: var(--color-primary);
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    padding: 20px 15px;
  }
  
  .register-wrapper {
    padding: 20px;
  }
  
  .register-title {
    font-size: 24px;
  }
  
  .verification-wrapper {
    flex-direction: column;
  }
  
  .interest-option {
    flex: 0 0 100%;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 12px;
  }
  
  .btn {
    width: 100%;
  }
  
  .btn-primary-container {
    justify-content: center;
  }
  
  .step-label {
    font-size: 12px;
  }
}
</style>